package com.carltechnology.mahjonggamecaculation.presenter.impl;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.carltechnology.mahjonggamecaculation.R;
import com.carltechnology.mahjonggamecaculation.base.MyAbstractSubscriber;
import com.carltechnology.mahjonggamecaculation.base.MyApplication;
import com.carltechnology.mahjonggamecaculation.dao.DataManager;
import com.carltechnology.mahjonggamecaculation.mode.IDetailGameData;
import com.carltechnology.mahjonggamecaculation.presenter.IMahjongDetailContentPresenter;
import com.carltechnology.mahjonggamecaculation.utils.Utils;
import com.carltechnology.mahjonggamecaculation.views.IMahjongDetailContentView;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by WZTCM on 2016/7/1.
 */
public class MahjongDetailContentPresenter implements IMahjongDetailContentPresenter {
    private IMahjongDetailContentView mView;
    private MyMahjongDetailAdapter adapter;

    private MahjongDetailContentPresenter(IMahjongDetailContentView mView) {
        this.mView = mView;
        adapter = new MyMahjongDetailAdapter();
        mView.getRecycleView().setAdapter(adapter);
    }


    public static MahjongDetailContentPresenter newInstance(IMahjongDetailContentView view) {
        return new MahjongDetailContentPresenter(view);
    }

    @Override
    public void showDetailInfo() {
        DataManager.getInstance()
                .getDataSourceHelper()
                .getMahjongDetailInfo(
                        MyApplication.getPool().getGameMode().getId(),
                        new MyDetailModeSubscriber());
    }



    private class MyDetailModeSubscriber extends MyAbstractSubscriber<IDetailGameData> {
        @Override
        public void onCompleted() {
            super.onCompleted();
            adapter.doCaculation();
        }

        @Override
        public void onNext(IDetailGameData mode) {
            adapter.add(mode);
        }
    }


    class MyMahjongDetailAdapter
            extends RecyclerView.Adapter<MyMahjongDetailAdapter.MyViewHolder> {
        private List<IDetailGameData> list;
        private MyCaculationObservable myCaculationObservable;

        public MyMahjongDetailAdapter() {
            list = new CopyOnWriteArrayList<>();
            myCaculationObservable = null;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.mahjongdetail_item_list_content, parent, false));

        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            IDetailGameData data = list.get(position);
            int[] prices = data.getValues();
            //holder.getLabelTextView().setText(position + ".");
            holder.getMoney1TextView().setText(prices[0] + "元");
            holder.getMoney2TextView().setText(prices[1] + "元");
            holder.getMoney3TextView().setText(prices[2] + "元");
            holder.getMoney4TextView().setText(prices[3] + "元");
            holder.getCostTextView().setText(data.getCost() + "元");
            holder.getPerunitTextView().setText(data.getUnit() + "元");
            holder.getDateTextView().setText(data.getDate());
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }

        public void add(IDetailGameData mode) {
            list.add(mode);
            notifyDataSetChanged();
        }

        public void delete(int pos) {
            list.remove(pos);
            notifyDataSetChanged();
        }

        public void clearUp() {
            list.clear();
            notifyDataSetChanged();
        }

        public void doCaculation(){
            if (myCaculationObservable==null){
                myCaculationObservable = new MyCaculationObservable();
            }
            for (IDetailGameData mode:list){
                myCaculationObservable.doCaculation(mode);
            }
            myCaculationObservable.doCaculation(null);
           // caculationCompleted();

        }
        private void caculationCompleted(){
            int [] res = {0,0,0,0,0};
            if (myCaculationObservable!=null){
                res[0] = myCaculationObservable.player1;
                res[1] = myCaculationObservable.player2;
                res[2] = myCaculationObservable.player3;
                res[3] = myCaculationObservable.player4;
                res[4] = myCaculationObservable.cost;
                myCaculationObservable.onCompleted();
                myCaculationObservable = null;
            }
            mView.getmDetailView().showCaculation(res);
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            @InjectView(R.id.mahjonggame_detail_money1)
            TextView money1TextView;
            @InjectView(R.id.mahjonggame_detail_money2)
            TextView money2TextView;
            @InjectView(R.id.mahjonggame_detail_money3)
            TextView money3TextView;
            @InjectView(R.id.mahjonggame_detail_money4)
            TextView money4TextView;
            @InjectView(R.id.mahjonggame_detail_cost)
            TextView costTextView;
            @InjectView(R.id.mahjonggame_detail_date)
            TextView dateTextView;
            @InjectView(R.id.mahjonggame_detail_perunit)
            TextView perunitTextView;

            public MyViewHolder(View itemView) {
                super(itemView);
                ButterKnife.inject(this, itemView);
            }


            public TextView getMoney1TextView() {
                return money1TextView;
            }

            public TextView getMoney3TextView() {
                return money3TextView;
            }

            public TextView getMoney2TextView() {
                return money2TextView;
            }

            public TextView getMoney4TextView() {
                return money4TextView;
            }

            public TextView getCostTextView() {
                return costTextView;
            }

            public TextView getDateTextView() {
                return dateTextView;
            }

            public TextView getPerunitTextView() {
                return perunitTextView;
            }
        }

        private class MyCaculationObservable {
            private final Observable<IDetailGameData> observable;
            private Subscriber<? super IDetailGameData> mySubs;
            //private Object lock;
            int player1;
            int player2;
            int player3;
            int player4;
            int cost;

            public MyCaculationObservable() {
                observable = Observable.create(new Observable.OnSubscribe<IDetailGameData>() {
                    @Override
                    public void call(Subscriber<? super IDetailGameData> subscriber) {
                        mySubs = subscriber;
                    }
                })
                        .onBackpressureBuffer(Utils.CONSTANT.ONBACKBUFFER_SIZE.getConstant())
                        .observeOn(Schedulers.computation());
                player1 = 0;
                player2 = 0;
                player3 = 0;
                player4 = 0;
                cost = 0;
                //lock = new Object();
                init(observable);

            }

            private void init(Observable<IDetailGameData> observable) {
                observable.subscribe(new Action1<IDetailGameData>() {
                    @Override
                    public void call(IDetailGameData iDetailGameData) {
                        if (iDetailGameData==null){
                            caculationCompleted();
                        }else{
                            int [] players = iDetailGameData.getValues();
                            //synchronized (lock){
                            player1+=players[0];
                            player2+=players[1];
                            player3+=players[2];
                            player4+=players[3];
                            cost+=iDetailGameData.getCost();
                        }
                    }
                });

            }

            public void doCaculation(IDetailGameData mode) {
                mySubs.onNext(mode);
            }

            public void onCompleted() {
                mySubs.unsubscribe();
            }

        }
    }


}
